package com.wf.controller;

import cn.hutool.core.util.StrUtil;
import com.thoughtworks.xstream.io.path.Path;
import com.wf.constant.MessageConstant;
import com.wf.constant.RedisConstant;
import com.wf.context.BaseContext;
import com.wf.domain.User;
import com.wf.dto.FileDTO;
import com.wf.exception.ApartmentException;
import com.wf.service.UserService;
import com.wf.utils.*;
import com.wf.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

/**
 * 文件上传接口
 * 处理文件上传相关请求
 */
@Slf4j
@RestController
@RequestMapping("/app")
@CrossOrigin
public class UpLoadController {

    @Autowired
    AliOssUtil aliOssUtil;

    @Autowired
    IdentificationUtil identificationUtil;

    @Autowired
    UserService userService;

    @Autowired
    RedisUtil redisUtil;

    /**
     * 上传文件
     *
     * @param file 待上传的文件
     * @return 文件的访问URL
     */
    @PostMapping("/upload")
    public Result upload(@RequestPart MultipartFile file) throws ApartmentException {

        // 生成新的文件名
        String objectName = FileNameUtils.getFileName(file.getOriginalFilename());

        try {
            // 调用aliOssUtil的upload方法上传文件，并获取上传后的文件路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);

            // 返回成功的结果，包含文件路径
            return Result.success(filePath);
        } catch (IOException e) {
            // 如果发生IO异常，记录错误日志
            log.error(e + "");
            throw new ApartmentException(MessageConstant.UPLOAD_FAILED);
        }

    }

    /**
     * 身份证识别
     *
     * @param file       待上传的文件
     * @param idCardSide 文件类型
     * @return
     * @throws IOException
     */
    @PostMapping("/uploadIdCard")
    public Result uploadIdCard(@RequestPart MultipartFile file, @RequestParam String idCardSide) throws IOException, ApartmentException {

        User user = new User();
        user.setUserId(BaseContext.getCurrentId());
        Map<String, Object> userInfo = identificationUtil.getUserInfo(file.getBytes(), idCardSide);
        if (StrUtil.equals(idCardSide, "front")) {
            Result upload = upload(file);
            userInfo.put("idCardFront", upload.getData());
            return updateUser(userInfo);

        } else {
            Result upload = upload(file);
            String uploadData = (String) upload.getData();
            user.setIdCardBack(uploadData);
            userService.updateById(user);
            return Result.success();
        }


    }

    @NotNull
    private Result updateUser(Map<String, Object> userInfo) {
        User user = new User();
        String idCardFront = (String) userInfo.get("idCardFront");
        user.setUserId(BaseContext.getCurrentId());
        user.setRealName((String) userInfo.get("realName"));
        user.setIdCard((String) userInfo.get("idCard"));
        user.setSex((String) userInfo.get("gender"));
        user.setIdCardFront(idCardFront);
        user.setIdCardType("身份证");
        redisUtil.set(RedisConstant.APARTMENT_USED_IMG, idCardFront);
        userService.updateById(user);
        return Result.success(user);
    }

    /**
     * Base64上传文件
     *
     * @param file 待上传的文件
     * @return 文件的访问URL
     */
    @PostMapping("/uploadBase64")
    public Result uploadBase64(@RequestBody String file) throws ApartmentException {

        MultipartFile multipartFile = BASE64DecodedMultipartFile.base64ToMultipart(file);
        // 生成新的文件名
        String objectName;
        if (multipartFile != null) {
            objectName = FileNameUtils.getFileName(multipartFile.getOriginalFilename());
            try {
                // 调用aliOssUtil的upload方法上传文件，并获取上传后的文件路径
                String filePath = aliOssUtil.upload(multipartFile.getBytes(), objectName);
                // 返回成功的结果，包含文件路径
                return Result.success(filePath);
            } catch (IOException e) {
                // 如果发生IO异常，记录错误日志
                log.error(e + "");
                throw new ApartmentException(MessageConstant.UPLOAD_FAILED);
            }
        }
        return Result.failure(MessageConstant.UPLOAD_FAILED);
    }
    /**
     * Base64身份证识别
     *
     * @param fileDTO 待上传的文件
     * @return
     */
    @PostMapping("/uploadIdCardBase64")
    public Result uploadBase64(@RequestBody FileDTO fileDTO) throws ApartmentException {

        Map<String, Object> userInfo = identificationUtil.getUserInfoByBase64(fileDTO);
        if (StrUtil.equals(fileDTO.getFile(), "front")) {
            return updateUser(userInfo);
        } else {
            return Result.success();
        }
    }
}
